package com.devteam.weatherforcecast;

import java.util.ArrayList;
import java.util.Calendar;

import android.app.PendingIntent;
import android.app.Service;
import android.appwidget.AppWidgetManager;
import android.appwidget.AppWidgetProvider;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.net.Uri;
import android.os.IBinder;
import android.util.Log;
import android.widget.RemoteViews;

import com.devteam.weather.WeatherCurrentCondition;
import com.devteam.weather.WeatherForecastCondition;

public class MainWidget extends AppWidgetProvider {
	Context context;
	private static final String TEXT_VALUE_KEY = "text";
	private static String preName = "Mypres";
	SharedPreferences prefs;
	static String UPDATE_ACTION = "ABC";
    static String s;
   
	@Override
	public void onReceive(Context context, Intent intent) {
		// TODO Auto-generated method stub
		String action = intent.getAction();
		if (action != null && action.equals(UPDATE_ACTION)) {
			Log.e("tham so thu nhat", s);
			// Build the widget update for today
			RemoteViews updateViews = buildUpdate(context, s);
			// Push update for this widget to the home screen
			ComponentName thisWidget = new ComponentName(context, MainWidget.class);
			AppWidgetManager manager = AppWidgetManager.getInstance(context);
			manager.updateAppWidget(thisWidget, updateViews);
		}

		else {
			super.onReceive(context, intent);
		}
	}

	public static RemoteViews buildUpdate(Context context, String s) {

		// Build an update that holds the updated widget contents
		/**
		 * Danh sách các dự báo của các ngày tiếp theo
		 */
		ArrayList<WeatherForecastCondition> listWeatherForecast = new ArrayList<WeatherForecastCondition>();
		/**
		 * Dự báo của ngày hiện tại
		 */
		WeatherCurrentCondition weatherCurrent;
		String linkData;
		RemoteViews updateViews = new RemoteViews(context.getPackageName(),
				R.layout.widget_layout);;
		weatherCurrent = new WeatherCurrentCondition();
		String s1=s.replaceAll("%20", " ");
		String s2=s1.replaceAll(",viet nam", "");
		s=s.replaceAll(" ", "");
		if (checkNetworkAvailable(context)==1) {
		linkData = "http://www.google.com/ig/api?weather=" + s;
		GoogleWeatherHandler a = new GoogleWeatherHandler(
				listWeatherForecast, weatherCurrent, linkData);
		a.parseData();
		weatherCurrent = a.getWeatherCurrentCondition();
		// Khoảng thời gian hiện tại
		Calendar ci = Calendar.getInstance();
		String time = ci.get(Calendar.MONTH)+1 + "."
				+ ci.get(Calendar.DAY_OF_MONTH) + "."
				+ ci.get(Calendar.YEAR);
			updateViews.setTextViewText(R.id.textView_doam,
					weatherCurrent.getDoAm());
			updateViews.setTextViewText(R.id.textView_gio,
					weatherCurrent.getTinhTrangGio());
			updateViews.setTextViewText(R.id.textView_ngay_diadiem, s2
					+ " - " + time);
			updateViews.setTextViewText(R.id.textView_nhietdo,
					weatherCurrent.getNhietDoC() + "°C");
			updateViews.setTextViewText(R.id.textView_tinhtrang,
					weatherCurrent.getTinhTrang());

			if (weatherCurrent.getTinhTrang().equals("Cloudy")) {
				updateViews.setTextViewText(R.id.textView_tinhtrang,
						"Có mây");
				updateViews.setImageViewResource(R.id.image_weather,
						R.drawable.symbol_1_3d);

			} else if (weatherCurrent.getTinhTrang().equals("Rain")) {
				updateViews.setTextViewText(R.id.textView_tinhtrang,
						"Có mưa");
				updateViews.setImageViewResource(R.id.image_weather,
						R.drawable.symbol_1_9d);

			} else if (weatherCurrent.getTinhTrang().equals("Light rain")) {
				updateViews.setTextViewText(R.id.textView_tinhtrang,
						"Mưa nhỏ");
				updateViews.setImageViewResource(R.id.image_weather,
						R.drawable.symbol_1_9d);

			} else if (weatherCurrent.getTinhTrang().equals("Thunderstorm")) {
				updateViews.setTextViewText(R.id.textView_tinhtrang,
						"Có dông");
				updateViews.setImageViewResource(R.id.image_weather,
						R.drawable.symbol_1_5d);

			} else if (weatherCurrent.getTinhTrang().equals(
					"Chance of Storm")) {
				updateViews.setTextViewText(R.id.textView_tinhtrang,
						"Có thể bão");
				updateViews.setImageViewResource(R.id.image_weather,
						R.drawable.symbol_1_11d);

			} else if (weatherCurrent.getTinhTrang()
					.equals("Mostly Cloudy")) {
				updateViews.setTextViewText(R.id.textView_tinhtrang,
						"Nhiều mây");
				updateViews.setImageViewResource(R.id.image_weather,
						R.drawable.symbol_1_15d);
				
			} else if (weatherCurrent.getTinhTrang().equals("Clear")) {
				updateViews.setTextViewText(R.id.textView_tinhtrang,
						"Trong sáng");
				updateViews.setImageViewResource(R.id.image_weather,
						R.drawable.symbol_1_2d);

			} else if (weatherCurrent.getTinhTrang().equals("Mostly Sunny")) {
				updateViews.setTextViewText(R.id.textView_tinhtrang,
						"Nắng gắt");
				updateViews.setImageViewResource(R.id.image_weather,
						R.drawable.symbol_1_1d);

			} else if (weatherCurrent.getTinhTrang().equals("Partly Sunny")) {
				updateViews.setTextViewText(R.id.textView_tinhtrang,
						"Nắng nhẹ");
				updateViews.setImageViewResource(R.id.image_weather,
						R.drawable.symbol_1_1d);

			} else if (weatherCurrent.getTinhTrang().equals("Sunny")) {
				updateViews.setTextViewText(R.id.textView_tinhtrang,
						"Nắng vừa");
				updateViews.setImageViewResource(R.id.image_weather,
						R.drawable.symbol_1_1d);

			} else if (weatherCurrent.getTinhTrang().equals("Overcast")) {
				updateViews.setTextViewText(R.id.textView_tinhtrang,
						"U ám");
				updateViews.setImageViewResource(R.id.image_weather,
						R.drawable.symbol_1_4d);
				
			} else if (weatherCurrent.getTinhTrang().equals(
					"Chance of Rain")) {
				updateViews.setTextViewText(R.id.textView_tinhtrang,
						"Có thể mưa");
				updateViews.setImageViewResource(R.id.image_weather,
						R.drawable.symbol_1_18d);
			}

		} else {
			updateViews.setTextViewText(R.id.textView_doam, "0");
			updateViews.setTextViewText(R.id.textView_gio, "0");
			updateViews.setTextViewText(R.id.textView_ngay_diadiem, "0");
			updateViews.setTextViewText(R.id.textView_nhietdo, "0");
			updateViews.setTextViewText(R.id.textView_tinhtrang,
					"Không có thông tin");
		}

		return updateViews;

	}

	@Override
	public void onUpdate(Context context, AppWidgetManager appWidgetManager,
			int[] appWidgetIds) {
		this.context = context;
		// TODO Auto-generated method stub
		context.startService(new Intent(context, UpdateService.class));
		Intent intent = new Intent(context, WeatherForecastActivity.class);
		intent.putExtra(AppWidgetManager.EXTRA_APPWIDGET_ID, appWidgetIds);
		intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
		intent.setData(Uri.parse(intent.toUri(Intent.URI_INTENT_SCHEME)));
		PendingIntent pendIntent = PendingIntent.getActivity(context, 0,
				intent, PendingIntent.FLAG_UPDATE_CURRENT);
		RemoteViews views = new RemoteViews(context.getPackageName(),
				R.layout.widget_layout);
		views.setOnClickPendingIntent(R.id.ll1, pendIntent);
		appWidgetManager.updateAppWidget(appWidgetIds, views);

		
		
	}

	public static int checkNetworkAvailable(Context c) {
		// get connection manager from system service
		ConnectivityManager manager = (ConnectivityManager) c
				.getSystemService(Context.CONNECTIVITY_SERVICE);
		// get network info status
		NetworkInfo netInfo = manager.getActiveNetworkInfo();
		// check availability status
		if (netInfo != null && netInfo.isAvailable()
				&& netInfo.isConnectedOrConnecting()) {
			return 1;
		}
		
			return 0;
	}

	public static class UpdateService extends Service {
		@Override
		public void onStart(Intent intent, int startId) {
			SharedPreferences prefs = getSharedPreferences(preName,
					MODE_PRIVATE);
			 s = prefs.getString(TEXT_VALUE_KEY, "BacNinh");
			Log.e("tham so thu nhat", s);
			// Build the widget update for today
			RemoteViews updateViews = buildUpdate(this, s);
			// Push update for this widget to the home screen
			ComponentName thisWidget = new ComponentName(this, MainWidget.class);
			AppWidgetManager manager = AppWidgetManager.getInstance(this);
			manager.updateAppWidget(thisWidget, updateViews);
		}

		

		@Override
		public IBinder onBind(Intent intent) {
			// We don't need to bind to this service
			return null;
		}

	}
}
